package com.itheima.mybaitstypehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.dto.Coord;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName CoordTypeHandler
 * @Description TODO
 * @Author Shinelon
 * @Date DATE 2021/8/11 18:18
 */
public class CoordTypeHandler implements TypeHandler<Coord> {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Coord coord, JdbcType jdbcType) throws SQLException {
        try {
            String s = objectMapper.writeValueAsString(coord);
            preparedStatement.setString(i,s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Coord getResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        try {
            return objectMapper.readValue(result,Coord.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;//失败
    }

    @Override
    public Coord getResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        try {
            return objectMapper.readValue(result,Coord.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;//失败


    }

    @Override
    public Coord getResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        try {
            return objectMapper.readValue(result,Coord.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;//失败
    }
}
